﻿'use strict';
const db = uniCloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  console.log('=== clearTestData 云函数开始 ===')
  console.log('1. 接收参数:', event)
  
  try {
    console.log('2. 清理测试数据...')
    
    // 定义测试数据的识别条件
    const testDataConditions = {
      sender_nickname: _.in(['测试用户', 'TestUser', '校园同学']),
      sender_user_id: _.in(['test123', '68c7719f99c624aa84820e5e'])
    };

    // 查询将要删除的测试数据数量
    const testDataCountResult = await db.collection('interaction-messages')
      .where(testDataConditions)
      .count();
    const deletedCount = testDataCountResult.total;

    // 删除所有测试数据
    const removeResult = await db.collection('interaction-messages')
      .where(testDataConditions)
      .remove();

    // 查询剩余的真实数据数量
    const remainingCountResult = await db.collection('interaction-messages')
      .where({
        target_user_id: event.userId,
        status: 'active',
        ..._.not(testDataConditions)
      })
      .count();
    const remainingCount = remainingCountResult.total;

    console.log('✅ 清理完成：删除了', deletedCount, '条测试数据，剩余', remainingCount, '条真实数据')

    return {
      code: 200,
      msg: '测试数据已清理',
      data: {
        deletedCount: deletedCount,
        remainingCount: remainingCount,
        removeResult: removeResult
      }
    };
  } catch (error) {
    console.error('❌ 清理测试数据失败:', error);
    return {
      code: 500,
      msg: '清理测试数据失败',
      error: error.message
    };
  }
};
